package controller

import (
	"time"
	"webstack/config"
	"webstack/util"

	"github.com/gin-gonic/gin"
)

type LoginForm struct {
	UserName string `json:"username" form:"username" binding:"required"`
	Password string `json:"password" form:"password" binding:"required"`
	TokenAge int    `json:"token_age" form:"token_age" binding:"required"`
}

// AdminLogin 后台管理员登陆
func AdminLogin(c *gin.Context) {
	var loginForm LoginForm
	if err := c.ShouldBind(&loginForm); err != nil {
		c.JSON(200, gin.H{
			"errcode": 15,
			"errMsg":  "登陆信息不全",
		})
		return
	}

	loginResult := loginForm.UserName == config.AdminUsername && loginForm.Password == config.AdminPassword
	if loginResult {
		tokenAge := config.TokenExpiredSecond
		if loginForm.TokenAge > 0 {
			tokenAge = loginForm.TokenAge
		}
		token, err := util.GenerateToken(loginForm.UserName, tokenAge)
		if err != nil {
			c.JSON(200, gin.H{
				"errcode": 25,
				"errMsg":  err.Error(),
			})
			return
		}

		nowTime := time.Now()
		expireTime := nowTime.Add(time.Duration(tokenAge) * time.Second)
		c.JSON(200, gin.H{
			"errcode": 0,
			"errMsg":  "",
			"data": gin.H{
				"_token":         token,
				"_token_expired": expireTime.Unix(),
			},
		})
	} else {
		c.JSON(200, gin.H{
			"errcode": 39,
			"errMsg":  "登陆失败",
		})
	}
}
